<?php
/**
 * 管理员操作日志
 * Created by PhpStorm.
 * User: ZFC
 * Date: 2015/6/8
 * Time: 17:48
 */

namespace common\models\DAO;


use common\models\CommonFunction;
use yii\db\ActiveRecord;

class AdminLog extends ActiveRecord {

    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'adminID' => '管理员ID',
            'type' => '事件类型',
            'createTime' => '时间',
            'ip' => 'IP',
            'result' => '结果',
            'controller' => '控制器名',
            'action' => '动作',
            'get' => 'GET参数',
            'post' => 'POST参数',
            'response' => '响应',
            'loginName' => '登录名',
        ];
    }

    /*
     * 记录管理员操作日志
     * @param $id
     * @param $type
     * @param string $controller 控制器ID
     * @param string $action 动作ID
     * @param string $param 请求参数
     * @throws \Exception
     */
    public static function addLog($id, $type, $controller = '', $action = '', $get = '', $post = ''){
        $adminLog = new AdminLog();
        $adminLog->adminID    = $id;
        $adminLog->type       = empty($type) ? '' : $type;
        $adminLog->controller = $controller;
        $adminLog->action     = $action;
        $adminLog->get        = $get;
        $adminLog->post       = $post;
        $adminLog->createTime = time();
        $adminLog->ip   = CommonFunction::get_client_ip();
        return $adminLog->save();
    }

    /**
     * 检查是否暴力登录
     * @param $userName string 输入的用户名
     * @param $ip string IP地址
     * @param $result bool 密码正确性
     * @return bool
     */
    public function checkForceLogin($loginName, $ip){
        $config = \Yii::$app->params['allow_login_fail_ip'];
        $check_time  = time() - $config['time'];
        $error_count_ip = $this->find()->where(['result' => 0, 'type' => 'LOGIN'])
            ->andWhere(['like', 'ip', $ip])
            ->andWhere(['>', 'createTime', $check_time])
            ->count();
        $error_count_name = $this->find()->where(['result' => 0, 'type' => 'LOGIN'])
            ->andWhere(['like', 'loginName', $loginName])
            ->andWhere(['>', 'createTime', $check_time])
            ->count();

        if(($error_count_ip > $config['count']) || ($error_count_name > $config['count'])){
            return false;
        }else{
            return true;
        }
    }

    /**
     * 记录登录日志
     * @param string $loginName 登录名
     * @param int $result 登录结果
     * @return bool
     */
    public static function addLoginLog($loginName, $result){
        $adminLog = new AdminLog();
        $adminLog->loginName  = $loginName;
        $adminLog->type       = 'LOGIN';
        $adminLog->createTime = time();
        $adminLog->ip         = CommonFunction::get_client_ip();
        $adminLog->result     = $result;
        return $adminLog->save();
    }
}